package com.siashan.unipay4j.ali.splitbill;

import com.alibaba.fastjson.JSON;
import com.alipay.api.request.AlipayTradeRoyaltyRelationBindRequest;
import com.alipay.api.response.AlipayTradeRoyaltyRelationBindResponse;
import com.siashan.unipay4j.ali.AbstractAliPay;
import com.siashan.unipay4j.core.Result;
import com.siashan.unipay4j.core.splitbill.BindModel;
import com.siashan.unipay4j.core.splitbill.ISplitBillRelationBind;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 支付宝分账关系绑定
 *
 * @author siashan
 * @since v1.0.1
 **/
@Slf4j
public class AliPaySplitBillRelationBind extends AbstractAliPay implements ISplitBillRelationBind {


    /**
     * 分账关系绑定成功标识
     */
    private static final String BIND_SUCCESS = "SUCCESS";

    /**
     * 分账关系绑定
     *
     * @param model       绑定参数
     * @return 绑定结果
     */
    @Override
    public Result bind(BindModel model) {
        log.debug("AliPaySplitBill => 订单{} 支付宝分账接收方绑定请求到达", model.getOutTradeNo());
        try {
            AlipayTradeRoyaltyRelationBindRequest request = new AlipayTradeRoyaltyRelationBindRequest();
            request.setBizContent(JSON.toJSONString(wrapParam(model)));
            AlipayTradeRoyaltyRelationBindResponse r = alipayClient.execute(request);
            log.debug("AliPaySplitBill => 订单{} 支付宝分账接收方绑定请求返回报文:{}", model.getOutTradeNo(), r);
            if (r.isSuccess()) {
                return BIND_SUCCESS.equals(r.getResultCode()) ? Result.tradeSuccess(r) : Result.tradeFail(r.getSubCode(), r.getSubMsg());
            }
            Result.returnFail(r.getSubCode(), r.getSubMsg());
        } catch (Exception e) {
            log.warn("AliPaySplitBill => 订单{} 支付宝分账接收方绑定请求异常", model.getOutTradeNo());
        }
        return Result.exception();
    }

    /**
     * 封装请求参数
     * @param model 请求实体
     * @return 请求参数
     */
    private Map<String, String> wrapParam(BindModel model) {
        Map<String, String> map = new HashMap<>();
        List<Map<String, String>> list = new ArrayList<>();

        Map<String, String> receiver = new HashMap<>();
        receiver.put("type", model.getType());
        receiver.put("account", model.getAccount());
        receiver.put("name", model.getName());
        receiver.put("memo", model.getCustomRelation());

        list.add(receiver);
        map.put("receiver_list", JSON.toJSONString(list));
        map.put("out_request_no", model.getOutTradeNo());

        return map;
    }
}
